package com.controller;

import com.bean.*;
import com.service.*;
import com.util.DateUtil;
import com.util.PageAssistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.*;

@Component
@Controller
@RequestMapping("buy")
public class BuyReturnController {

    @Autowired
    private BookingService bookingService;
    @Autowired
    private SeatService seatService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CdyOrderService cdyOrderService;
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private MovieService movieService;
    @Autowired
    private FilmsService filmsService;

    @RequestMapping("buyTicket")
    public String query(HttpSession session, Model model, Movie movie, PageAssistant<Movie> paMovie, Booking booking){
        System.out.println(">>>>>>>>>>> buyTicket query");
        System.out.println(">>>>>>>>> buy ");
        System.out.println(booking);
        System.out.println(movie);
        System.out.println("-------------------");
        movie.setState(1);
        List<Movie> movies = movieService.find(movie);
        model.addAttribute("movies",movies);
        System.out.println(movies);
        return "page/buyAndReturn/choose";
    }

    @RequestMapping("select")
    public String select(HttpSession session, Model model, Movie movie, PageAssistant<Films> paFilms){
        System.out.println(">>>>>>>>>>> buyTicket select");
        System.out.println(">>>>>>>>> select ");
        System.out.println(movie);
        Map<String,Object> map = new HashMap<>();

        //获取日历工具
        Calendar cal = Calendar.getInstance();
        //获取当前总毫秒数
        long timeInMillis = cal.getTimeInMillis();
        //设置至少提前15分钟买票
        long ticketTime = timeInMillis+15*60*1000;

        map.put("movieId",movie.getId());
        String startDate = DateUtil.format(new Date(), "yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //可以提前买票的最大时间(3天)
        c.add(Calendar.DATE,4);
        String stopDate = DateUtil.format(c.getTime(),"yyyy-MM-dd");
        map.put("startDate",startDate);
        map.put("stopDate",stopDate);

        System.out.println(map.toString());
        //获取所有的选中id的影片
        paFilms.setItems(filmsService.query(map));
        System.out.println(paFilms.getItems().size()+"<><><><><><>查出来的东西");
        int size = paFilms.getItems().size();
        ArrayList<Films> films = new ArrayList<>();
        for (int i = 0; i <size ; i++) {
            //若排片表中影片播放时间小于预设可提前买票的最小时间
            if (paFilms.getItems().get(i).getStartTime().getTime() < ticketTime ){
                System.out.println(ticketTime);
                System.out.println(paFilms.getItems().get(i).getStartTime().getTime());
                //不显示该场电影
                System.out.println(paFilms.getItems());
            }else{
                //当前时间判断可以买票
                films.add(paFilms.getItems().get(i));
                }
        }

        if (films.size() != 0){
            paFilms.setCount(films.size());
            System.out.println("<><><><><><"+paFilms.getCount());
        }else{
            paFilms.setSize(1);
            paFilms.setCount(1);
        }
        System.out.println(paFilms.getItems());
        model.addAttribute("films",films);
        model.addAttribute("paFilms",paFilms);
        return "page/buyAndReturn/filmsList";
    }

    @RequestMapping("show")
    public String show(Model model, Films films){

        System.out.println(films.getId());
        List<Films> films1 = filmsService.find(films);
        model.addAttribute("film",films1.get(0));
        System.out.println("<><><>><><><><<+"+films1.get(0));
        Booking booking = new Booking();
        //设置影厅
        booking.setHall(films1.get(0).getCinemaId());
        booking.setTime(films1.get(0).getStartTime());
        //查询电影院座位信息
        Cinema cinema = new Cinema();
        cinema.setId(films1.get(0).getCinemaId());
        List<Cinema> cinemas = cinemaService.find(cinema);

        System.out.println(booking);
        System.out.println("该影厅编号:"+cinemas.get(0).getId());
        System.out.println("该影厅有座位:"+cinemas.get(0).getSeat());
        //找到该影厅的第一号位置的Id(1排1号)
        Seat seat1 = new Seat();
        seat1.setCinemaId(cinemas.get(0).getId());
        seat1.setRows(1);
        seat1.setNumber(1);
        List<Seat> seats1 = seatService.find(seat1);
        System.out.println("这是该影厅的一号位的Id:"+seats1.get(0).getId());

        //存放判断好座位是否能用的信息
        HashMap<Integer,Integer> seatState = new HashMap<>();
        //存放座位选座信息
        ArrayList<Integer> arr = new ArrayList<>();
        //imax厅
        if(cinemas.get(0).getSeat() == 348){
            //所有该片的有效订单
            booking.setState(0);
            List<Booking> bookings = bookingService.find(booking);
            System.out.println("这是该影厅的所有购票:"+bookings);
            //根据订单找到具体座位信息
            for (int i = 0; i <bookings.size() ; i++) {
                Seat seat = new Seat();
                seat.setId(bookings.get(i).getSpare());
                //找到唯一对应的座位
                List<Seat> seats = seatService.find(seat);
                System.out.println("这是查出来的座位:"+seats.get(0).toString());
                //判断座位的选中状态

               if (seats.get(0).getChoose().split(",").length > 1){
                   String[] split = seats.get(0).getChoose().split(",");
                   for (int j = 0; j <split.length ; j++) {
                       //若已购
                       if(split [j].equals(films1.get(0).getId()+"")){
                           seatState.put(seats.get(0).getId(),1);
                       }
                   }
               }else{
                   //只有一场排片的状态
                    if (seats.get(0).getChoose().equals(films1.get(0).getId()+"")){
                        seatState.put(seats.get(0).getId(),1);
                    }
               }
            }

            System.out.println("这是选中的座位号:"+seatState.keySet());

            for (int i = seats1.get(0).getId(); i <seats1.get(0).getId()+348 ; i++) {
                //若没有,则加选中座位号为 i,状态为0
                if(!seatState.keySet().contains(i)){
                    arr.add(0);
                }else{
                    arr.add(1);
                }
            }

            System.out.println("这是选中和没选中的状态号:"+arr.toString());
            System.out.println("这是添加的集合数量:"+seatState.size());
            model.addAttribute("seatState",arr);
            return "page/buyAndReturn/movie";

        }else{
            //所有该片的有效订单
            booking.setState(0);
            List<Booking> bookings = bookingService.find(booking);
            System.out.println("这是该影厅的所有购票:"+bookings);
            //根据订单找到具体座位信息
            for (int i = 0; i <bookings.size() ; i++) {
                Seat seat = new Seat();
                seat.setId(bookings.get(i).getSpare());
                //找到唯一对应的座位
                List<Seat> seats = seatService.find(seat);
                System.out.println("这是查出来的座位:"+seats.get(0).toString());
                //判断座位的选中状态
                if (seats.get(0).getChoose().split(",").length > 1){
                    String[] split = seats.get(0).getChoose().split(",");
                    for (int j = 0; j <split.length ; j++) {
                        //若已购
                        if(split [j].equals(films1.get(0).getId()+"")){
                            seatState.put(seats.get(0).getId(),1);
                        }
                    }
                }else{
                    //只有一场排片的状态
                    if (seats.get(0).getChoose().equals(films1.get(0).getId()+"")){
                        seatState.put(seats.get(0).getId(),1);
                    }
                }
            }
            System.out.println("这是选中的座位号:"+seatState.keySet());
            System.out.println("这是选中的座位号状态集合:"+seatState.values());

            for (int i = seats1.get(0).getId(); i <seats1.get(0).getId()+187 ; i++) {
                //若没有,则加选中座位号为 i,状态为0
                if(!seatState.keySet().contains(i)){
                    arr.add(0);
                }else{
                    arr.add(1);
                }
            }
            System.out.println("这是选中和没选中的状态号:"+arr.toString());
            model.addAttribute("seatState",arr);

            return "page/buyAndReturn/movieSmall";
        }
    }


    @RequestMapping("buyCommodity")
    public String buyCommodity(HttpSession session, Commodity commodity, Model model, PageAssistant<Commodity> paCommodity, CdyOrder cdyOrder){
        System.out.println(">>>>>>>>>>> buyCommodity query");
        System.out.println(">>>>>>>>> buy ");

        System.out.println("-------------------");
        commodity.setState(0);
        List<Commodity> commodities = commodityService.find(commodity);
        model.addAttribute("commodities",commodities);
        System.out.println(commodities);
        return "page/buyAndReturn/chooseCommodity";
    }

    @RequestMapping("selectCommodity")
    public String selectCommodity(HttpSession session, Commodity commodity, Model model, CdyOrder cdyOrder){
        System.out.println(">>>>>>>>>>> selectCommodity query");
        System.out.println(">>>>>>>>> buy ");

        System.out.println("-------------------");
        commodity.setState(0);
        List<Commodity> commodities = commodityService.find(commodity);
        model.addAttribute("commodities",commodities);
        System.out.println(commodities);
        return "page/buyAndReturn/chooseCommodity";
    }

    @RequestMapping("returnCommodity")
    public  String returnCommodity(){
        return "page/buyAndReturn/returnCommodity";
    }

    @Transactional
    @RequestMapping("checkCommodity")
    public String checkCommodity(HttpSession session, Model model, CdyOrder cdyOrder, Commodity commodity) {
        System.out.println("checkCommodity");
        System.out.println(cdyOrder);
        System.out.println(model);
        System.out.println(commodity);
        System.out.println("---------------------");
        //查询订单相关
        List<CdyOrder> cdyOrders = cdyOrderService.find(cdyOrder);
        if (cdyOrders.size() > 0){
            CdyOrder c = cdyOrders.get(0);
            //修改库存
            Date date = new Date();

            if (c.getOrderTime().getTime()+ 60*60*1000 < date.getTime()||c.getState() == 1 || c.getState() == 2){
                System.out.println("对不起,超过一小时的商品订单或者该订单已经退货成功,或者已经参加过活动,我们不予办理!");
                return "page/buyAndReturn/false";
            }else{
                commodity.setId(c.getCdyName());
                //查询到要修改的commodity信息
                List<Commodity> commodities = commodityService.find(commodity);
                Commodity co = commodities.get(0);
                System.out.println(co+"修改前");
                int num = co.getStock()+c.getNumber();
                co.setStock(num);
                System.out.println(co+"修改后");
                int modify = commodityService.modify(co);
                c.setState(1);
                int modify1 = cdyOrderService.modify(c);
                System.out.println(modify+"1成功");
                System.out.println(modify1+"1成功");
                return "page/buyAndReturn/ok";
            }
        }else{
            System.out.println("对不起,没有该订单,我们不予办理!");
            return "page/buyAndReturn/false";
        }
    }

    @RequestMapping("returnTicket")
    public String returnTicket(){
        return "page/buyAndReturn/returnTicket";
    }

    @Transactional
    @RequestMapping("checkTicket")
    public String checkTicket(HttpSession session, Model model, Booking booking, Movie movie) {
        System.out.println("checkTicket");
        System.out.println(movie);
        System.out.println(model);
        System.out.println(booking);
        System.out.println("---------------------");
        //查询订单相关
        List<Booking> bookings = bookingService.find(booking);
        if (bookings.size() > 0){
            Booking b = bookings.get(0);
            //修改库存
            Date date = new Date();

            if (b.getOrderTime().getTime()+ 10*60*1000 < b.getTime().getTime()|| b.getState() == 1 || b.getState() == 2){
                System.out.println("对不起,提前10分钟退票或者您的票已经受理过退票,或者没有该订单信息,或者参加过活动,我们不予办理!");
                return "page/buyAndReturn/false";
            }else{
                //修改座位相关信息
            }
            return "page/buyAndReturn/ok";
        }else{
            return "page/buyAndReturn/false";
        }
    }
    
}
